#include<iostream>
#include<string>
#include<cerrno>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
const int s=1024;
string getOtherMessage()
{
    static int cnt=0;
    string messageid=to_string(cnt);
    cnt++;
    pid_t self_id=getpid();
    string stringpid=to_string(self_id);
    string message="messageid: ";
    message+=messageid;
    message+="my pid is : ";
    message+=stringpid;
    return message;
}

void SubProcessWrite(int wfd)
{
    int pipesize=0;
    string message="father ,I am your son prcess!";
    char c ='A';
    while (true)
    {
        cerr << "+++++++++++++++++++++++++++++++++" <<endl;
        string info = message + getOtherMessage(); // 这条消息，就是我们子进程发给父进程的消息
        sleep(1);
        write(wfd, info.c_str(), info.size()); // 写入管道的时候，没有写入\0, 有没有必要？没有必要
        
        std::cerr << info << std::endl;
    }
}
void FatherProcessRead(int rfd)
{
    char inbuffer[s];
    while(true)
    {
       
        cout<<"----------------------------------"<<endl;
        ssize_t n=read(rfd,inbuffer,sizeof(inbuffer)-1);
                if (n > 0)
        {
            inbuffer[n] = 0; // == '\0'
            std::cout  << "傻逼"<<inbuffer << std::endl;
        }
        else if (n == 0)
        {
            // 如果read的返回值是0，表示写端直接关闭了，我们读到了文件的结尾
            std::cout << "client quit, father get return val: " << n << " father quit too!" << std::endl;
            break;
        }
        else if(n < 0)
        {
            std::cerr << "read error" << std::endl;
            break;
        }
    }
}
int main()
{
    int pipefd[2];
    int n=pipe(pipefd);
    if(n!=0)
    {
        cerr<<"errno:"<<errno<<":"<<"errstring"<<strerror(errno)<<endl;
        return 1;
    }
    cout<<"pipefd[0]"<<pipefd[0]<<",pipefd[1]"<<pipefd[1]<<endl;
    sleep(1);
    pid_t id=fork();
    if(id==0)
    {
        cout<<"子进程关闭不需要的fd了，准备发消息了"<<endl;
        //子进程---write
        //3.关闭不需要的fd
        close(pipefd[0]);
        SubProcessWrite(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    cout<<"父进程关闭不需要fd了，准备收消息"<<endl;
    close(pipefd[1]);
    FatherProcessRead(pipefd[0]);
    cout<<"5s,father close rfd"<<std::endl;
    close(pipefd[0]);
    int status=0;
    pid_t rid=waitpid(id,&status,0);
    if(rid>0)
    {
      cout<<"wait child process done, exit sig:"<<(status&0x7f)<<endl;
      cout<<"wait child process done,exit code(ign):"<<((status>>8)&0xFF)<<endl;
    }

    return 0;
}
